package com.aaron.spring.jdbc;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.aaron.startup.SpringStartup;

public class JdbcTemplateUtilsImpl<T> implements JdbcTemplateUtils<T>
{

    private static JdbcTemplate jdbcTemplate;

    private static DataSourceTransactionManager transaction;

    static
    {
        if (null == jdbcTemplate)
        {
            jdbcTemplate = SpringStartup.getIntance().loadJdbcTemplate();
            transaction = SpringStartup.getIntance().loadTransactionManager();
        }
    }

    @Override
    public T queryObjectById(String sql, Integer[] ids, RowMapper rowMapper)
    {
        // TODO Auto-generated method stub
        return (T) jdbcTemplate.queryForObject(sql, ids, rowMapper);
    }

    @Override
    public List<Map<String, Object>> queryList(String sql, Object[] args)
    {
        // TODO Auto-generated method stub
        return jdbcTemplate.queryForList(sql, args);
    }

    @Override
    public void operationObject(String sql, final Object[] args)
    {
        // TODO Auto-generated method stub
        jdbcTemplate.update(sql, new PreparedStatementSetter()
        {

            @Override
            public void setValues(PreparedStatement ps) throws SQLException
            {
                // TODO Auto-generated method stub
                for (int i = 0; i < args.length; i++)
                {
                    ps.setObject((i + 1), args[i]);
                }
            }

        });

    }

}
